<template>
  <div>
    <h1>添加医院</h1>
    <el-form label-width="120px" @submit.native.prevent="add_hospitel">
      <el-form-item label="添加院名">
        <el-input v-model="hospitel.name" placeholder="添加一个医院来保存所在医院的数据"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit">添加</el-button>
      </el-form-item>
    </el-form>
    <h1>添加数据到院区</h1>
    <el-form label-width="120px">
      <el-form-item label="选择院区">
        <el-select v-model="value" filterable placeholder="请选择">
          <el-option
            v-for="item in hospitel_list"
            :key="item._id"
            :label="item.name"
            :value="item._id"
          ></el-option>
        </el-select>
        <el-checkbox v-model="checked" style="margin-left:20px">是否覆盖</el-checkbox>
      </el-form-item>
      <el-form-item>
        <el-upload
          :auto-upload="false"
          :on-change="handleFile"
          :before-remove="beforeRemove"
          :on-exceed="handleExceed"
          :limit="1"
          action
        >
          <el-button size="small" type="primary">选择表格</el-button>
          <div slot="tip" class="el-upload__tip">解析导入表到所选院区</div>
        </el-upload>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import XLSX from "xlsx";

export default {
  data() {
    return {
      value: "",
      hospitel: {},
      hospitel_list: [],
      fields: ["设备名称", "68码", "是否计量", "风险等级", "折旧年限(年)"],
      checked: false
    };
  },
  watch: {
    hospitel_list: function() {
      this.value = this.hospitel_list[0]._id;
    }
  },
  created() {
    this.fetch_data();
  },
  methods: {
    getOnlyDevs(array) {
      let only_name = new Array();
      let only_devs = new Array();
      array.forEach(item => {
        if (only_name.indexOf(item["设备名称"]) == -1) {
          only_name.push(item["设备名称"]);
          only_devs.push(item);
        }
      });
      return only_devs;
    },
    handleFile(e) {
      let f = e.raw;
      let reader = new FileReader();
      reader.onload = async e => {
        let data = new Uint8Array(e.target.result);
        let workbook = XLSX.read(data, { type: "array" });
        let name = workbook.SheetNames[0];
        let worksheet = workbook.Sheets[name];
        let only_devs_json = this.getOnlyDevs(
          XLSX.utils.sheet_to_json(worksheet)
        );
        let devs = only_devs_json.map(item => {
          let obj = new Object();
          this.fields.forEach(field => {
            if (item[field] == undefined) {
              item[field] = "";
            }
            obj[field] = item[field];
          });
          obj.hospitel_id = this.value;
          return obj;
        });
        let res = null;
        if (!this.checked) {
          res = this.$http.post("devs", {
            devs,
            hospitel_id: this.value
          });
        }
        else{
          res = this.$http.put("devs", {
            devs,
            hospitel_id: this.value
          });
        }
        res
          .then(data => {
            let { type, message } = data.data;
            this.$message({
              message,
              type
            });
            this.fetch_data();
          })
          .catch(() => {
            this.$message({
              message: "添加数据失败",
              type: "error"
            });
          });
      };
      reader.readAsArrayBuffer(f);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${
          files.length
        } 个文件，不可选择 ${files.length + fileList.length} 个文件`
      );
    },
    beforeRemove(file) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    fetch_data() {
      this.$http.get("hospitels").then(value => {
        this.hospitel_list = value.data;
      });
    },
    add_hospitel() {
      this.$http
        .post("hospitels", this.hospitel)
        .then(() => {
          this.$message({
            message: "创建医院成功",
            type: "success"
          });
          this.fetch_data();
        })
        .catch(() => {
          this.$message({
            message: "创建医院失败",
            type: "error"
          });
        });
    }
  }
};
</script>

<style></style>
